import axios from 'axios'
import qs from 'qs'
import Utils from './util'


/* 请求头类型 */
//formData类型
const FORM_DATA_TYPE = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
}
//JSON类型
const JSON_TYPE = {
    headers: {
        'Content-Type': 'application/json'
    }
}

//短信验证类型
const text_TYPE = {
    headers: {
        'Content-Type': 'application/json',
    }
}

const timeout = 60000

//创建axios实例
const service = axios.create({
    timeout: timeout
})

//请求拦截器
service.interceptors.request.use(config => {

    const appCode = 'c935dd24487a4627af35fc0f0d50c327'
    //添加请求头的配置信息
    config.headers.Authorization = Utils.getTooken()
    //请求前将参数转为相对应类型
    if (config.method === 'get') {
        if (config.headers['Content-Type'] === 'application/json') {
            return config
        } else {
            config.data = qs.stringify(config.data)
        }
    } else if (config.method === 'post') {
        if (config.headers['Content-Type'] === 'application/json') {
            config.headers.Authorization='APPCODE ' + appCode
            return config
        } else {
            config.data = qs.stringify(config.data)
        }
    }
    return config
}, error => {
    console.log('service request', error)
    Promise.reject(error)
})

export default{
    //post请求 fromData参数类型
    post: function (url, params, successCallBack, errorCallBack) {
        service.post(url, params, FORM_DATA_TYPE)
            .then(function (response) {
                if (response && response.code.toString() === "200") {
                    successCallBack(response)
                } else {
                    errorCallBack(response)
                }
            }).catch(function (error) {
                errorCallBack(error)
            })
    },
    //psot JSONT
    postJson: function (url, params, successCallBack, errorCallBack) {
        service.post(url, params, JSON_TYPE)
            .then(function (response) {
                if (response && response.code.toString() === "200") {
                    successCallBack(response)
                } else {
                    errorCallBack(response)
                }
            }).catch(function (error) {
                errorCallBack(error)
            })
    },
    //post Query
    postJson: function (url, params, successCallBack, errorCallBack) {
         url = url + '?' + Utils.urlEncode(params)
        service.post(url,{}, text_TYPE)
            .then(function (response) {
                // console.log(response)
                if (response && response.status == 200) {
                    successCallBack(response)
                } else {
                    errorCallBack(response)
                }
            }).catch(function (error) {
                errorCallBack(error)
            })
    },

}
